<?php


namespace app\services;

use app\BaseController;
use app\lib\exception\AuthException;
use app\lib\exception\ParamException;
use app\lib\exception\ServiceException;

use app\model\Users;
use app\Request;
use app\utils\JWTUtil;

use think\captcha\facade\Captcha;
use think\facade\Cache;
use think\facade\Session;




class AuthService
{
    public function setToken($user)
    {
        $token = (new JWTUtil())->signToken($user->id);

        Cache::store('redis')->set($token, json_encode($user));

        return $token;
    }

    public function getToken($token)
    {
        return Cache::store('redis')->get($token);
    }
    public function delToken($token)
    {
        return Cache::store('redis')->delete($token);
    }


    public function login($username, $password)
    {
        $usersDao = new Users();
        $user = $usersDao->where('username', $username)->find();

        if ($user == null || !$user->validatePassword($password)){
            throw new ParamException("账号或密码错误");
        }



        $usersDao->where('id',$user['id'])->update(['login_date'=>time()]);
        $user->login_date = time();
        return ['token' => $this->setToken($user), 'user' => $user];
    }


    public function checkingRole($token, $role)
    {
        if (empty($token)) throw new AuthException('未登入');
        $usersDao = new Users();
        $userJson = $this->getToken($token);
        if ($userJson == null) throw new AuthException('未登入');

        if ($role == null){
            return $usersDao->find(json_decode($userJson, true)['id']);
        }
        return $usersDao->where('role',$role)->find(json_decode($userJson, true)['id']);
    }


}
